package com.paw.ruoyi.admin.core.util;

import javax.servlet.http.HttpServletRequest;

public class RemoteRequestUtils {

  private RemoteRequestUtils() {
  }

  /**
   * 获取远程请求客户端的IP地址
   *
   * @param request
   *            the HttpServletRequest
   * @return 远程请求客户端的IP地址
   */
  public static String getRemoteIP(HttpServletRequest request) {
    String sources = "x-forwarded-for,X-Forwarded-For,X-Real-IP,Proxy-Client-IP,WL-Proxy-Client-IP,HTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR";
    String[] sourceArrays = sources.split(",");
    for (String source : sourceArrays) {
      String remoteIP = request.getHeader(source);
      if (remoteIP != null && remoteIP.trim().length() > 0 && !"unknown".equalsIgnoreCase(remoteIP)) {
        remoteIP = remoteIP.trim();
        int commaOffset = remoteIP.indexOf(',');
        if (commaOffset < 0) {
          return remoteIP;
        }
        return remoteIP.substring(0, commaOffset);
      }
    }
    return request.getRemoteHost();
  }
}
